//
//  LoginByCodeController.m
//  HaiGeEr_Student
//
//  Created by liuchen on 2018/9/9.
//  Copyright © 2018年 海格尔. All rights reserved.
//

//static修饰全局计时值
static int timeValue = 60;
#import "LoginByCodeController.h"
#import "LoginResetSecretController.h"
#import "LoginBySecretController.h"
#import "WKWebController.h"
#import "LoginByCodeView.h"
#import "UserModel.h"

@interface LoginByCodeController ()
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,weak) UIButton *backBtn;
@property (nonatomic,weak) UIButton *loginBtn;
@property (nonatomic,weak) LoginByCodeView *loginByCodeView;
@end

@implementation LoginByCodeController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    if (nil != _timer) {
        [_timer invalidate];
        _timer = nil;
        
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubView];
}

#pragma mark ==========创建视图==========
- (void)createSubView{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, SYSTEM_STATUSBAR_HEGHT, 83*SCALEUNIT, 83*SCALEUNIT);
    [backBtn setImage:[UIImage imageNamed:@"8-4-1"] forState:UIControlStateNormal];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(30*SCALEUNIT, 35*SCALEUNIT, 30*SCALEUNIT, 35*SCALEUNIT)];
    [backBtn addTarget:self action:@selector(backChange:) forControlEvents:UIControlEventTouchUpInside];
    _backBtn = backBtn;
    [self.view addSubview:self.backBtn];
    
    LoginByCodeView *loginByCodeView = [[LoginByCodeView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backBtn.frame), [UIScreen mainScreen].bounds.size.width, 495*SCALEUNIT)];
    [loginByCodeView.loginBySecretBtn addTarget:self action:@selector(backChange:) forControlEvents:UIControlEventTouchUpInside];
    [loginByCodeView.codeBtn addTarget:self action:@selector(codeChange:) forControlEvents:UIControlEventTouchUpInside];
    [loginByCodeView.userAgreementBtn addTarget:self action:@selector(JumpToUserAgreement:) forControlEvents:UIControlEventTouchUpInside];
    _loginByCodeView = loginByCodeView;
    [self.view addSubview:self.loginByCodeView];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    loginBtn.frame = CGRectMake(70*SCALEUNIT, CGRectGetMaxY(self.loginByCodeView.frame)+85*SCALEUNIT, 610*SCALEUNIT, 90*SCALEUNIT);
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn.titleLabel setFont:[UIFont systemFontOfSize:LoginFont]];
    [loginBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [loginBtn setBackgroundColor:LOGINBUTTONBACKRGBA];
    [loginBtn.layer setShadowColor:[UIColor blackColor].CGColor];
    [loginBtn.layer setShadowOffset:CGSizeMake(5*SCALEUNIT, 5*SCALEUNIT)];
    [loginBtn.layer setShadowOpacity:0.8];
    [loginBtn addTarget:self action:@selector(loginIn:) forControlEvents:UIControlEventTouchUpInside];
    _loginBtn = loginBtn;
    [self.view addSubview:self.loginBtn];
}

#pragma mark ==========发送验证码==========
- (void)codeChange:(UIButton *)btn{
    btn.userInteractionEnabled = NO;
    if (isEmpty(self.loginByCodeView.phoneView.textField.text)) {
        [self showMessage:@"手机号不能为空"];
    } else if (!LOGINPHONECHECK(self.loginByCodeView.phoneView.textField.text)){
        [self showMessage:@"手机号格式错误"];
    }else {
        [self showLoading];
        NSDictionary *dic = [NSDictionary dictionaryWithObject:self.loginByCodeView.phoneView.textField.text forKey:@"phone"];
        [[NetworkEngine sharedClient] GET:LOGINSENDCODE data:dic success:^(id responseObject) {
            [self showSuccess:[responseObject objectForKey:@"msg"]];
            if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
                //开启计时器
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];
            } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    }
    btn.userInteractionEnabled = YES;
}

#pragma mark ==========登录==========
- (void)loginIn:(UIButton *)btn{
    if (isEmpty(self.loginByCodeView.phoneView.textField.text)) {
        [self showMessage:@"请输入手机号"];
    }else if (isEmpty(self.loginByCodeView.codeView.textField.text)) {
        [self showMessage:@"请输入验证码"];
    }else if (!LOGINPHONECHECK(self.loginByCodeView.phoneView.textField.text)) {
        [self showMessage:@"手机号格式错误"];
    }else if (!self.loginByCodeView.selectJudge) {
        [self showMessage:@"请勾选用户协议"];
    }else {
        NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                    self.loginByCodeView.phoneView.textField.text, @"phone",
                                    self.loginByCodeView.codeView.textField.text, @"code",
                                    @"1", @"loginType", nil];
        [self showLoading];
        [[NetworkEngine sharedClient] GET:LGGINBYPASSWORD data:parameters success:^(id responseObject) {
            [self hideHUD];
            if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
                [UserMessage sharedInstance].model = [UserModel mj_objectWithKeyValues:[responseObject objectForKey:@"data"]];
                [[NSUserDefaults standardUserDefaults] setObject:[responseObject objectForKey:@"data"] forKey:@"userMessage"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self jumpToMainPage];
            } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
        } failure:^(NSString *error) {
            [self hideHUD];
        }];
    }
}
- (void)jumpToMainPage{
    if ([[UserMessage sharedInstance].model.loginTime length]==0) {
        LoginResetSecretController *vc = [[LoginResetSecretController alloc] init];
        vc.resetJudge = NO;
        vc.phone = self.loginByCodeView.phoneView.textField.text;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        [[UIApplication sharedApplication].delegate window].rootViewController = [CoachTabBarController shareLZHTabbarController];
        [[[UIApplication sharedApplication].delegate window] makeKeyAndVisible];
    }
}

#pragma mark ==========用户协议==========
- (void)JumpToUserAgreement:(UIButton *)btn{
    WKWebController *wkWeb = [[WKWebController alloc]init];
    //NSString *filePath = [[NSBundle mainBundle] pathForResource:@"UserProtocol" ofType:@"html"];
    //NSURL *url = [[NSURL alloc] initWithString:filePath];
    wkWeb.url = [[NSBundle mainBundle] URLForResource:@"UserProtocol.html" withExtension:nil];
    [self.navigationController pushViewController:wkWeb animated:YES];
}

#pragma mark ==========定时器方法==========
- (void)dealYzmBut{
    
    UIButton *sender = self.loginByCodeView.codeBtn;
    if (timeValue == 0) {
        [sender setTitle:@"重新发送" forState:UIControlStateNormal];
        sender.userInteractionEnabled = YES;
        timeValue = 60;
        [self.timer invalidate];
        return;
    }
    
    sender.userInteractionEnabled = NO;
    [sender setTitle:[NSString stringWithFormat:@"%d",timeValue] forState:UIControlStateNormal];
    timeValue--;
}

#pragma mark ==========返回上一层==========
- (void)backChange:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc{
    NSLog(@"完事儿");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
